<template>
    <div id="accessUser">
        <search-table
            :columns="accessListColumns"
            :data="accessGroupList"
            :total="groupTotal"
            :page.sync="queryGroupInfo.pageIndex"
            :size.sync="queryGroupInfo.pageSize"
            @change-size="changeSize"
            @change-page="changePage"
        >
            <Alert type="error" show-icon v-if="showDuplicateNameTip" slot="alert">
                <p>不同{{ type === 10 ? '角色' : '团队' }}中存在相同成员，请删除</p>
            </Alert>
            <template slot="button-group">
                <!-- :disabled="
                        disabledAllBtn ||
                        (groupTotal >= subnetList.length && [1, 8, 9].includes(type)) ||
                        allPartyAreDisabled
                    " -->
                <Button
                    type="primary"
                    ghost
                    @click="openUserAccessModal"
                    icon="md-add"
                    v-if="hideBtnAdd"
                    :disabled="disabledAllBtn"
                    >{{ this.type === 10 ? '添加角色 ' : '添加团队' }}</Button
                >
                <!-- 夺旗赛的附加功能，暂时隐藏 -->
                <!-- <Button type="primary" ghost @click="automatic" v-if="type == 2" icon="md-options"
                  :disabled="disabledAllBtn">一键配置团队</Button>
              <Button type="primary" ghost icon="md-cloud-download" @click="doOutputUser"
                  :disabled="accessGroupList.length == 0" v-if="type == 2">导出用户信息</Button> -->
            </template>
            <template slot="input-group">
                <Input v-model="teamName" placeholder="名称" @on-change="getDataBounce" clearable />
            </template>
        </search-table>
        <Modal
            v-model="accessUserModal.show"
            :title="accessUserModal.title"
            :width="920"
            :loading="accessUserModal.loading"
            @on-cancel="refreshAccessGroupList"
            :mask-closable="false"
            footer-hide
        >
            <AccessUserTransfer
                :selectGroup="currGroup"
                :show="accessUserModal.show"
                :type="type"
                :hwType="hwType"
                :ctfVpn="ctfVpn"
                @delSceneUsers="delSceneUsers"
                :isDistributed="isDistributed"
            ></AccessUserTransfer>
        </Modal>
        <Modal
            v-model="accessGroupModal.show"
            :title="accessGroupModal.title"
            :width="600"
            @on-ok="addOrUpdateAccessGroup"
            @on-cancel="handleReset"
            @on-visible-change="visibleChange"
            :loading="accessGroupModal.loading"
            :mask-closable="false"
        >
            <Form
                ref="groupFormValidate"
                :model="groupFormValidate"
                :rules="groupRuleValidate"
                :label-width="80"
            >
                <FormItem label="名称" prop="name">
                    <Input
                        v-model.trim="groupFormValidate.name"
                        placeholder="请输入名称"
                        :maxlength="50"
                    ></Input>
                </FormItem>
                <FormItem
                    label="势力方"
                    prop="partyId"
                    v-if="type != 7 && type != 10 && hlConfig != 2"
                >
                    <Select filterable
                        v-model="groupFormValidate.partyId"
                        placeholder="请选择势力方"
                        filterable
                        @on-open-change="uncheck"
                        :disabled="accessGroupModal.type == 'modify'"
                    >
                        <Option
                            :value="party.id.toString()"
                            :title="party.name"
                            :disabled="party.disable || party.name === '管理员势力方'"
                            :label="party.name"
                            v-for="party in partyList"
                            :key="party.id"
                        >
                            <span>{{ party.name }}</span>
                            <span
                                :style="{
                                    float: 'right',
                                    padding: '6px',
                                    backgroundColor:
                                        'rgba(' +
                                        party.red +
                                        ',' +
                                        party.green +
                                        ',' +
                                        party.blue +
                                        ',' +
                                        party.alpha +
                                        ')',
                                }"
                            ></span>
                        </Option>
                    </Select>
                </FormItem>
                <FormItem :label="`${isSupergroup ? '大组名称' : '描述'}`" prop="description">
                    <Input
                        type="textarea"
                        :maxlength="200"
                        :rows="4"
                        v-model.trim="groupFormValidate.description"
                        :placeholder="`请输入${isSupergroup ? '大组名称' : '描述'}`"
                    ></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal
            v-model="accessNetworkModal.show"
            :title="accessNetworkModal.title"
            :width="400"
            :loading="accessNetworkModal.loading"
            @on-ok="batchUserToDevice"
            :mask-closable="false"
        >
            <Alert type="warning" show-icon v-if="type == 1">
                <p style="color: #f90">切换环境的注意事项：</p>
                <p>
                    1.如果是动态Flag任务，需要先删除之前的动态Flag任务，然后根据当前使用的环境新建动态Flag任务。
                </p>
                <p>2.Checker任务需要根据当前使用的环境新建Checker任务</p>
                <p>
                    3.需要进Flag持续提交任务中查看系统根据环境切换默认新建的Flag持续提交任务是否启动，如果没有启动，请手动启动。
                </p>
                <p>
                    4.如果需要用到选手自带答题设备接入，切换环境之后，需要在“选手自带答题设备接入申请”中更换对应的绑定。
                </p>
            </Alert>
            <Alert type="warning" show-icon v-if="[8, 9].includes(type)">
                <p style="color: #f90">切换环境的注意事项：</p>
                <p>1.Checker任务需要根据当前使用的环境新建Checker任务</p>
                <p>
                    2.如果需要用到选手自带答题设备接入，切换环境之后，需要在“选手自带答题设备接入申请”中更换对应的绑定。
                </p>
            </Alert>
            <Alert type="warning" show-icon v-if="type == 2 && onlineMode == 0">
                如果需要用到选手自带答题设备接入，切换环境之后，需要在“选手自带答题设备接入申请”中更换对应的绑定。
            </Alert>
            <Select filterable
                v-model="selBackupSubnet"
                placeholder="请选择环境"
                @on-change="getAllVms"
                filterable
            >
                <Option
                    :value="subnet.id"
                    :label="subnet.name"
                    :title="subnet.name"
                    v-for="subnet in avaiSubnetList"
                    :key="subnet.id"
                ></Option>
            </Select>
        </Modal>
         <Modal v-model="userModel" title="接入用户" width="550" footer-hide>
            <div class="userModel">
                <Tag
                type='border'
                :color="item.online ? 'primary' : 'error'"
                :name="item.id"
                v-for="(item, index) in userList"
                :key="index" >
                    <Icon type="ios-person-outline" size ='16'/>
                    <span
                     class="user_list_line"
                     :style="{borderLeft :item.online ? '1px dashed #2d8cf0': '1px dashed #ed4014'}"
                    ></span>
                    <span>{{ item.userName + '-' + (item.online ? '在线-' + item.ip : '离线') }}</span>
                </Tag>
            </div>
        </Modal>
    </div>
</template>

<script>
import AccessUserTransfer from '@/view/drill_compete/page/accessUserTransfer.vue';
import {
    getaccessgrouplist,
    setuservmrelation,
    delsceneusers,
    getpartylist,
    delaccessgroup,
    addaccessgroup,
    modifyaccessgroup,
    getUserInstanceExclude,
} from '@/api/access_new';
import { getstatusbyprjid } from '@/api/drill';
import {
    setautomatic,
    queryNetworkList,
    delGroupTarget,
    getUserLoginIP,
    banAccessGroup_new,
    allowAccessGoup_new,
    outputUser,
    switchCtfGameBox,
    queryCtfTargetAllot,
    queryTargetAllot,
    allotTopic2Team,
    delAssignedTopics,
    getSpareEnvList,
    getTargetTeamList_new,
    delTeamTarget,
} from '@/api/drill_compete';
import { getDeviceList } from '@/api/drill';
import { getCompanyUsersInfo } from '@/api/users';
import { sendToSence } from '@/api/boardcast_new.js';
import TableTooltip from '@/view/drill_compete/page/tableTooltip.vue';
import SearchTable from '@/components/SearchTable/SearchTable';
import addFlagCommitLoopFun from '@/view/drill_compete/page/task_new/addFlagCommitLoopFun.js';
import { mapMutations } from 'vuex';
import { debounce } from '@/libs/utils';

export default {
    name: 'scenes',
    components: {
        AccessUserTransfer,
        TableTooltip,
        SearchTable,
    },
    props: [
        'type',
        'disabledAllBtn',
        'step',
        'onlineMode', //线上/线下
        'vmInEnable',
        'isSupergroup',
        'allowChangeIp',
        'configMode',
        'hlConfig',
        'isDistributed',
        'hwType',
        'hwExtentionType',
        'showBtn',
        'vpn', //vpn模式
    ],
    mixins: [addFlagCommitLoopFun],
    data() {
        return {
            teamName: '', // 搜索条件，团队名称
            allPartyAreDisabled: true,
            projectId: this.$route.query.prjid,
            testId: this.$route.query.id,
            currGroup: {},
            listStyle: {
                width: '290px',
                height: '300px',
            },
            project: {
                drillitemname: this.$route.query.name,
                projectid: this.$route.query.prjid,
                drillitemid: this.$route.query.id,
                testId: this.$route.query.id,
                testid: this.$route.query.id,
            },
            usedAccessList: [],
            partyList: [],
            accessGroupList: [],
            accessGroupModal: {
                show: false,
                loading: true,
                title: `添加${this.type === 10 ? '角色' : '团队'}`,
                type: 'add',
            },
            accessUserModal: {
                show: false,
                loading: true,
                title: '接入/移除用户',
            },
            queryGroupMemberInfo: {
                testId: this.$route.query.id,
                pageIndex: 1,
                pageSize: 10,
            },
            groupMemberTotal: 0,
            projectGroupMemberList: [],
            groupFormValidate: {
                name: '',
                partyId: '',
                description: '',
            },
            groupRuleValidate: {
                name: [{ required: true, message: '不能为空', trigger: 'change' }],
                partyId: [{ required: true, message: '不能为空', trigger: 'change' }],
            },
            accessListColumns: [
                {
                    title: '名称',
                    key: 'name',
                    align: 'center',
                    width: 230,
                    placement: 'top-left',
                    order: 1,
                    tooltip: true,
                },
                {
                    title: '创建者',
                    key: 'creatorName',
                    align: 'center',
                    width: 120,
                    tooltip: true,
                },
                {
                    title: '创建时间',
                    key: 'created',
                    align: 'center',
                    minWidth:140,
                },
                {
                    title: this.hwExtentionType == 2?'团队用户':'已接入用户',
                    key: 'userList',
                    align: 'center',
                    minWidth:300,
                    render: (h, params) => {
                        let copyList = Array.from(params.row.userList)
                        let arrEl = copyList && copyList.length > 3 ? copyList.slice(0, 2) : copyList
                        let arr = arrEl.map((user) => {
                            return h(
                                'Tag',
                                {
                                    props: {
                                        type: 'border',
                                        color: user.online ? 'primary' : 'error',
                                        name: user.id,
                                    },
                                },
                                [
                                    h('Icon', {
                                        attrs: {
                                            type: 'ios-person-outline',
                                            size: 16,
                                        },
                                        style: {
                                            'margin-top': '-2px',
                                        },
                                    }),
                                    h('span', {
                                        style: {
                                            display: 'inline-block',
                                            width: 0,
                                            height: '100%',
                                            margin: '0 8px',
                                            borderLeft: user.online
                                                ? '1px dashed #2d8cf0'
                                                : '1px dashed #ed4014',
                                            verticalAlign: 'middle',
                                        },
                                    }),
                                    h(
                                        'span',
                                        {},
                                        user.userName +
                                        '-' +
                                        (user.online ? '在线-' + user.ip : '离线')
                                    ),
                                ]
                            );
                        });
                        return h(
                            'div',
                            {
                                style: {
                                    display: 'flex',
                                    'flex-wrap': 'wrap',
                                },
                            },
                            arr.length === 0 ? '无' : [arr, h('Button', {
                                props: {
                                    type: 'info',
                                    size: 'small',
                                    // disabled: params.row.userList && params.row.userList.length == 0
                                },
                                style: {
                                    display: copyList.length > 2 ? 'block' : 'none'
                                },
                                on: {
                                    click: () => {
                                        this.handleUserNumber(params.row.userList)
                                    }
                                }
                            }, '查看')]
                        );
                    },
                },
                {
                    title: '封禁状态',
                    key: 'ban',
                    align: 'center',
                    placement: 'top-right',
                    minWidth:100,
                    render: (h, params) => {
                        return h(
                            'Tag',
                            {
                                props: {
                                    color: this.groupBanned(params.row) ? 'var(--status-no)' : 'var(--status-yes)',
                                },
                            },
                            this.groupBanned(params.row) ? '已封禁' : '未封禁'
                        );
                    },
                },
                {
                    title: '操作',
                    width: 260,
                    key: 'action',
                    opList: [
                        {
                            txt: '切换环境',
                            disabled: (data) => {
                                return this.disabledAllBtn || data.spare;
                            },
                            show: () => {
                                return this.allowSwitchingEnvironments ? true : false;
                            },
                            fun: (data) => {
                                this.selBackupSubnet = '';
                                this.accessNetworkModal.show = true;
                                this.currentNetworkId = data.networkId
                                this.$set(this.accessNetworkModal, 'group', data);
                                if ([1, 8, 9].includes(this.type)) {
                                    // 攻防赛、攻防赛Plus需要查询可用的备用环境
                                    this.getSpareEnvList();
                                }
                            }
                        },
                        {
                            txt: (data) => {
                                return this.groupBanned(data) ? '解禁' : '封禁'
                            },
                            tooltip: true,
                            title: (data) => {
                                return this.groupBanned(data) ? '确定解禁？' : '确定封禁？'
                            },
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            fun: (data) => {
                                this.groupBanned(data) ? this.allowAccessGroup(data) : this.banAccessGroup(data)
                            }
                        },
                        {
                            txt: '接入/移除',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            show:(data) => {
                                return !(this.step == 'mid' || this.configMode === 1) 
                            },
                            fun: (data) => {
                                this.currGroup = data;
                                this.accessUserModal.show = true;
                            }
                        },
                        {
                            txt: '修改',
                            type: 'modify',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            show:(data) => {
                                return !(this.step == 'mid' || this.configMode === 1)
                            },
                            fun: (data) => {
                                this.accessGroupModal.type = 'modify';
                                this.accessGroupModal.title =
                                   this.type === 10 ? '修改角色 ' : '修改团队';
                                this.accessGroupModal.show = true;
                                this.groupFormValidate = {
                                    id: data.id,
                                    name: data.name,
                                    partyId: data.partyId,
                                    description: data.description
                                };
                            }
                        },
                        {
                            txt: '删除',
                            tooltip: true,
                            type: 'delete',
                            title: '确认删除？',
                            disabled: () => {
                                return this.disabledAllBtn;
                            },
                            show:(data) => {
                                let url = this.$route.name
                                return !(this.step == 'mid' || this.configMode === 1) &&
                                    !(url.includes('fzDrillDetail')||url.includes('zcDrillDetail')||url.includes('newHwDetail'))
                            },
                            fun: this.delAccessGroup
                        }
                    ]
                },
                {
                    title: '操作',
                    width: 270,
                    key:'action1',
                    placement: 'top-right',
                    show:false,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        disabled: this.disabledAllBtn || params.row.spare,
                                    },
                                    attrs: {
                                        title: '切换环境',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        display: this.allowSwitchingEnvironments
                                            ? 'inline-block'
                                            : 'none',
                                    },
                                    on: {
                                        click: () => {
                                            this.selBackupSubnet = '';
                                            this.accessNetworkModal.show = true;
                                            this.$set(this.accessNetworkModal, 'group', params.row);
                                            this.currentNetworkId = params.row.networkId;
                                            if ([1, 8, 9].includes(this.type)) {
                                                // 攻防赛、攻防赛Plus需要查询可用的备用环境
                                                this.getSpareEnvList();
                                            }
                                        },
                                    },
                                },
                                [
                                    // h('img', {
                                    //     attrs: {
                                    //         src:
                                    //             this.disabledAllBtn || params.row.spare
                                    //                 ? require('../../../assets/scene/dis-switch-network.png')
                                    //                 : require('../../../assets/scene/switch-network.png'),
                                    //     },
                                    //     style: {
                                    //         cursor: 'pointer',
                                    //         'vertical-align': 'middle',
                                    //         display: 'inline-block',
                                    //         marginBottom: '4px',
                                    //     },
                                    // }),
                                    h('span', {
                                        style: {
                                            cursor: 'pointer',
                                            color: this.disabledAllBtn || params.row.spare ? '#c5c8ce' : '#1563C2',
                                        },
                                    },'切换环境'),
                                ]
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        confirm: true,
                                        'ok-text': '确定',
                                        'cancel-text': '取消',
                                        type: 'error',
                                        size: 'large',
                                        title:
                                            '确定' +
                                            (this.groupBanned(params.row) ? '解禁?' : '封禁?'),
                                        transfer: true,
                                    },
                                    attrs: {
                                        title: this.groupBanned(params.row) ? '解禁' : '封禁',
                                    },
                                    style: {},
                                    on: {
                                        'on-ok': () => {
                                            if (this.groupBanned(params.row)) {
                                                this.allowAccessGroup(params.row);
                                            } else {
                                                this.banAccessGroup(params.row);
                                            }
                                        },
                                    },
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: 'primary',
                                                size: 'small',
                                                disabled: this.disabledAllBtn,
                                            },
                                            attrs: {
                                                title: this.groupBanned(params.row)
                                                    ? '解禁'
                                                    : '封禁',
                                            },
                                            style: {
                                                border: 'none',
                                                background: 'none',
                                                boxShadow: 'none',
                                            },
                                            on: {
                                                click: () => {},
                                            },
                                        },
                                        [
                                            h('img', {
                                                attrs: {
                                                    src: this.groupBanned(params.row)
                                                        ? this.disabledAllBtn
                                                            ? require('../../../assets/scene/dis-allow-compete.png')
                                                            : require('../../../assets/scene/allow-compete.png')
                                                        : this.disabledAllBtn
                                                        ? require('../../../assets/scene/dis-ban-compete.png')
                                                        : require('../../../assets/scene/ban-compete.png'),
                                                },
                                                style: {
                                                    cursor: 'pointer',
                                                    'vertical-align': 'middle',
                                                    display: 'inline-block',
                                                    marginBottom: '4px',
                                                },
                                            }),
                                            h('span', {
                                                style: {
                                                    cursor: 'pointer',
                                                    color: '#2d8cf0',
                                                },
                                            }),
                                        ]
                                    ),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: this.disabledAllBtn,
                                    },
                                    attrs: {
                                        title: '接入/移除',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        display:
                                            this.step == 'mid' || this.configMode === 1
                                                ? 'none'
                                                : 'inline-block',
                                    },
                                    on: {
                                        click: () => {
                                            this.currGroup = params.row;
                                            this.accessUserModal.show = true;
                                        },
                                    },
                                },
                                [
                                    h('img', {
                                        attrs: {
                                            src: this.disabledAllBtn
                                                ? require('../../../assets/scene/dis-access.png')
                                                : require('../../../assets/scene/access.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'vertical-align': 'middle',
                                            display: 'inline-block',
                                            marginBottom: '4px',
                                        },
                                    }),
                                    h('span', {
                                        style: {
                                            cursor: 'pointer',
                                            color: '#2d8cf0',
                                        },
                                    }),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                        disabled: this.disabledAllBtn,
                                    },
                                    attrs: {
                                        title: '修改',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        display:
                                            this.step == 'mid' || this.configMode === 1
                                                ? 'none'
                                                : 'inline-block',
                                    },
                                    on: {
                                        click: () => {
                                            this.accessGroupModal.type = 'modify';
                                            this.accessGroupModal.title =
                                                this.type === 10 ? '修改角色 ' : '修改团队';
                                            this.accessGroupModal.show = true;
                                            this.groupFormValidate = {
                                                id: params.row.id,
                                                name: params.row.name,
                                                partyId: params.row.partyId,
                                                description: params.row.description,
                                            };
                                        },
                                    },
                                },
                                [
                                    h('img', {
                                        attrs: {
                                            src: this.disabledAllBtn
                                                ? require('../../../assets/project/modifys.png')
                                                : require('../../../assets/project/modifys-h.png'),
                                        },
                                        style: {
                                            cursor: 'pointer',
                                            'vertical-align': 'middle',
                                            display: 'inline-block',
                                            marginBottom: '4px',
                                        },
                                    }),
                                    h('span', {
                                        style: {
                                            cursor: 'pointer',
                                            color: '#2d8cf0',
                                        },
                                    }),
                                ]
                            ),
                            h(
                                'Poptip',
                                {
                                    props: {
                                        confirm: true,
                                        'ok-text': '确定',
                                        'cancel-text': '取消',
                                        type: 'error',
                                        size: 'large',
                                        title: '确定删除?',
                                        transfer: true,
                                    },
                                    attrs: {
                                        title: '删除',
                                    },
                                    style: {
                                        display:
                                            this.step == 'mid' || this.configMode === 1
                                                ? 'none'
                                                : 'inline-block',
                                    },
                                    on: {
                                        'on-ok': () => {
                                            this.delAccessGroup(params.row);
                                        },
                                    },
                                },
                                [
                                    h(
                                        'Button',
                                        {
                                            props: {
                                                type: 'text',
                                                size: 'small',
                                                disabled: this.disabledAllBtn,
                                            },
                                            style: {
                                                border: 'none',
                                                background: 'none',
                                                boxShadow: 'none',
                                            },
                                        },
                                        [
                                            h('img', {
                                                attrs: {
                                                    src: this.disabledAllBtn
                                                        ? require('../../../assets/project/delNote-d.png')
                                                        : require('../../../assets/project/delNote-h.png'),
                                                },
                                                style: {
                                                    cursor: 'pointer',
                                                    'vertical-align': 'middle',
                                                    display: 'inline-block',
                                                    marginBottom: '4px',
                                                    display: this.hideBtnAdd ? 'inline-block' : 'none',
                                                },
                                            }),
                                            h('span', {
                                                style: {
                                                    cursor: 'pointer',
                                                    color: '#2d8cf0',
                                                },
                                            }),
                                        ]
                                    ),
                                ]
                            ),
                        ]);
                    },
                },
            ],
            queryGroupInfo: {
                pageIndex: 1,
                pageSize: 10,
                testId: this.$route.query.id,
            },
            groupTotal: 0,
            projectInfo: {},
            subnetList: [],
            //却换环境
            backupSubnetList: [], //备用环境列表
            selBackupSubnet: '', //当前选择的备用环境
            accessNetworkModal: {
                show: false,
                loading: true,
                title: '切换环境',
                group: {},
            },
            networkVms: [], //子网络下的虚拟机
            showDuplicateNameTip: false,
            targetAllotList: [],
            targetAllotTotal: 0,
            currentNetworkId: '',
            spareEnv: [],
            userModel: false,
            userList: [],
        };
    },
    filters: {},
    computed: {
        avaiSubnetList() {
            // 计算可用的备用环境
            if ([1, 8, 9].includes(this.type)) {
                //攻防不允许使用相同环境，需要过滤掉已经使用的环境作为可选项
                if (this.backupSubnetList.length > 0 && this.spareEnv.length > 0) {
                    let spareEnvIds = [];
                    this.spareEnv.forEach((item) => {
                        if (item.status === 0) {
                            // 未被使用的备用环境
                            spareEnvIds.push(item.networkId);
                        }
                    });
                    return this.backupSubnetList.filter((item) => spareEnvIds.includes(item.id));
                } else {
                    return [];
                }
            } else {
                // 夺旗可以使用相同的环境
                if (this.currentNetworkId) {
                    return this.backupSubnetList.filter(
                        (item) => item.id !== this.currentNetworkId
                    );
                } else {
                    return this.backupSubnetList;
                }
            }
        },
        isNoReuse() {
            // 红蓝、攻防、护网势力方不允许重复使用
            return [0, 1, 5, 8, 9].includes(this.type);
        },
        allowSwitchingEnvironments() {
            // 攻防赛、夺旗赛允许切换环境
            return [1, 2, 8, 9].includes(this.type);
        },
        hideBtnAdd(){
            return this.showBtn == false ? this.showBtn : this.configMode !== 1
        },
        ctfVpn(){
            return this.type === 2 && this.onlineMode === 1 && this.vpn
        }
    },
    mounted() {
        this.getAccessGroupList();
        this.getAllAccessList();
        if (this.allowSwitchingEnvironments) {
            // 允许切换环境，查询工程信息
            this.getProjectInfo();
        }
        if (this.type != 7 && this.type != 10 && this.hlConfig != 2) {
            // 非综合演练有势力方的展示列
            this.accessListColumns.splice(1, 0, {
                title: '势力方',
                key: 'partyName',
                align: 'center',
                width: 100,
                render: (h, params) => {
                    return h(
                        'Tooltip',
                        {
                            class: 'tableTooltip',
                            props: {
                                maxWidth: 400,
                                placement: 'top',
                                triggle: 'hover',
                                transfer: true,
                            },
                            style: {
                              color: params.row.partyColor.replace('rgb(55,62,104)','#2d8cf0'),
                            },
                        },
                        [
                            h(
                                'p',
                                {
                                    class: 'showContent',
                                    style: {
                                        maxWidth: '100px',
                                    },
                                },
                                params.row.partyName
                            ),
                            h(
                                'div',
                                {
                                    class: 'tooltipContent',
                                    slot: 'content',
                                },
                                params.row.partyName
                            ),
                        ]
                    );
                },
            });
        }
        if (this.type == 5 && this.hwExtentionType != 2) {
            // 护网演练(除日常渗透)需要额外展示团队的外网IP
            this.accessListColumns.splice(4, 0, {
                title: '外网IP',
                key: 'ip',
                align: 'center',
                width: 100,
                tooltip: true,
            });
        }
    },
    methods: {
        ...mapMutations('board', ['setRefresTimestamp']),
        ...mapMutations('compet', ['setRefreshChatRoom']),
        handleUserNumber (item) {
            this.userModel = true
            this.userList = item
        },
        getSpareEnvList() {
            getSpareEnvList(this.testId)
                .then(({ code, message, data }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                        return;
                    } else {
                        this.spareEnv = data.items || [];
                    }
                })
                .catch(() => {
                    this.$Message.error('查询备用环境异常');
                });
        },
        // 下拉框关闭时，点击body，让输入框失去焦点，用来修复iview表单中下拉框的怪异bug
        uncheck(type) {
            if (!type) {
                document.body.click();
            }
        },
        // 防抖封装，团队名改变时，延迟更新列表数据
        getDataBounce: debounce(function () {
            this.changePage();
        }),
        // 打开添加模态框，查询所有势力方和已使用的接入组
        openUserAccessModal() {
            this.accessGroupModal.show = true;
            this.accessGroupModal.type = 'add';
            this.accessGroupModal.title = `添加${this.type === 10 ? '角色' : '团队'}`;
            this.getAllAccessList();
        },
        // 一键配置团队，当前版本该功能暂时隐藏
        automatic() {
            let id = this.$route.query.id;
            setautomatic(id).then((data) => {
                if (data.code == 1) {
                    this.getAccessGroupList();
                    this.$Message.success('自动分配成功！');
                }
            });
        },
        // 接入/移除用户的模态框隐藏后，更新接入组数据，通知vuex查询更新相关数据
        refreshAccessGroupList() {
            this.getAccessGroupList();
            this.setRefresTimestamp();
        },
        // 查询竞赛、演练接入组列表
        getAccessGroupList() {
            if (!this.testId) {
                return;
            }
            getaccessgrouplist(
                Object.assign(this.queryGroupInfo, {
                    name: this.teamName,
                })
            ).then((data) => {
                if (data.code == 1) {
                    this.accessGroupList = data.data.items;
                    this.groupTotal = data.data.total;
                    this.accessGroupList.forEach((group) => {
                        if (this.type == 5) {
                            // 护网演练需要额外查询团队的外网ip用于展示
                            this.getOptionalVms(group);
                        }
                        this.getNetworkDetails(group);
                        let userList = group.userList;
                        let userIds = userList.map((user) => user.userId);
                        userList.forEach((user) => {
                            this.getCompanyUsersInfo(user.userId).then((online) => {
                                // 获取在线状态
                                this.$set(user, 'online', online);
                            });
                        });
                        this.getUserLoginIP(userIds).then((data) => {
                            // 获取用户登录IP地址
                            userList.forEach((user) => {
                                this.$set(user, 'ip', '');
                                if (data.length > 0) {
                                    let ips = data
                                        .filter((item) => item.userId == user.userId)
                                        .map((item) => item.loginIpAddress);
                                    if (ips.length > 0) {
                                        this.$set(user, 'ip', ips[0]);
                                    }
                                }
                            });
                        });
                    });
                    if (this.step == 'pre') {
                        // 赛前，人员有变化发送事件，提示需要重新交验是否可以开始竞赛或演练
                        this.$emit('setHasUser', '');
                    }
                } else if (data.code == -2) {
                    this.accessGroupList = [];
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 修改当前页，默认首页
        changePage(page = 1) {
            this.queryGroupInfo.pageIndex = page;
            this.getAccessGroupList();
        },
        // 修改分页大小，默认10条数据
        changeSize(size = 10) {
            this.queryGroupInfo.pageSize = size;
            this.getAccessGroupList();
        },
        // 获取已经使用的接入组，和所有势力方，可用于判断是否需要禁用添加团队按钮
        getAllAccessList() {
            if (!this.testId) {
                return;
            }
            let params = {
                pageIndex: 1,
                pageSize: 2147483647,
                testId: this.$route.query.id,
            };
            this.allPartyAreDisabled = false;
            // 查询已有的接入组，判断接入组成员是否重复
            getaccessgrouplist(params).then((data) => {
                if (data.code === 1) {
                    this.usedAccessList = data.data.items;
                    let allSelUserIds = [
                        ...this.usedAccessList
                            .map((team) => team.userList.map((user) => user.userId))
                            .flat(),
                    ];
                    if ([...new Set(allSelUserIds)].length != allSelUserIds.length) {
                        // 组中成员有重复
                        this.showDuplicateNameTip = true;
                    } else {
                        this.showDuplicateNameTip = false;
                    }
                    this.getPartyList();
                } else {
                    this.$Message.error(data.data.message);
                }
            });
        },
        // 查询场景下所有可用的势力方
        getPartyList() {
            if (!this.projectId) {
                return;
            }
            let params = { projectId: this.projectId };
            getpartylist(params).then((data) => {
                if (data.code == 1) {
                    // 滤掉默认势力方
                    let partyList = data.attribute.dataList || [];
                    if (this.type !== 7 && this.type != 10) {
                        // 非综合演练的场景需要过滤掉默认势力方
                        partyList = partyList.filter((party) => party.name != '默认势力方');
                    }
                    let useredPartyList1 = new Set(
                        this.usedAccessList.map((usedParty) => usedParty.partyId)
                    );
                    let useredPartyList = [...useredPartyList1];
                    // 势力方不允许重复使用，并且用完后，禁用添加团队按钮
                    if (this.isNoReuse && partyList.length <= useredPartyList.length) {
                        if (this.type === 0 && [1, 2].includes(this.hlConfig)) {
                            this.allPartyAreDisabled = false;
                        } else {
                            this.allPartyAreDisabled = true;
                        }
                    }
                    // 护网演练存在一个管理员势力方，这个团队不允许普通团队使用
                    if (this.type === 5) {
                        let manageParty =
                            partyList.find((item) => item.name === '管理员势力方') || {};
                        // 管理员势力方没有使用，可使用的势力方需要减一
                        if (!useredPartyList.includes(String(manageParty.id))) {
                            this.allPartyAreDisabled =
                                partyList.length - 1 <= useredPartyList.length;
                        } else {
                            this.allPartyAreDisabled = partyList.length <= useredPartyList.length;
                        }
                    }
                    // if (this.type != 0) {
                        partyList.forEach((party) => {
                            let id = party.id + '';
                            if (this.isNoReuse) {
                                // 势力方不允许重复使用
                                if(!(this.type === 0 && [1, 2].includes(this.hlConfig))){ // 对抗演练0模式还是要限制势力方不允许重复使用
                                    party.disable = useredPartyList.includes(id);
                                }
                            } else {
                                party.disable = false;
                            }
                        });
                    // }
                    this.partyList = partyList;
                } else if (data.code == -2) {
                    this.partyList = [];
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 清空团队添加、修改模态框的数据和校验信息
        handleReset() {
            this.$refs['groupFormValidate'].resetFields();
        },
        // 隐藏模态框时的回调函数
        visibleChange(type) {
            if (!type) {
                this.handleReset();
            }
        },
        // 添加或修改团队
        addOrUpdateAccessGroup() {
            if (!this.testId) {
                // 场景id
                return;
            }
            this.$refs['groupFormValidate'].validate((valid) => {
                if (valid) {
                    let party;
                    if (
                        this.type == 7 ||
                        this.type == 10 ||
                        (this.type == 0 && this.hlConfig == 2)
                    ) {
                        // 综合演练、应急防御演练没有势力方区分，使用第一个即可
                        party = this.partyList[0];
                    } else {
                        party = this.partyList.filter(
                            (party) => party.id == this.groupFormValidate.partyId
                        )[0];
                    }
                    if (party === undefined) {
                        this.$Message.warning(
                            `工程不存在可用的势力方，无法添加${this.type === 10 ? '角色' : '团队'}`
                        );
                        return;
                    }
                    let params = {
                        testId: this.testId,
                        partyId: party.id,
                        name: this.groupFormValidate.name,
                        partyColor: `rgba(${party.red},${party.green},${party.blue},${party.alpha})`,
                        description: this.groupFormValidate.description,
                    };
                    if (this.accessGroupModal.type == 'add') {
                        // 添加操作
                        addaccessgroup(params).then((data) => {
                            if (data.code == 1) {
                                this.$Message.info(`添加${this.type === 10 ? '角色' : '团队'}成功`);
                                this.$emit('add-data');
                                this.teamName = '';
                                this.accessGroupModal.show = false;
                                this.getAllAccessList(); // 添加团队，需要确认添加团队按钮是否还能点击
                                this.getAccessGroupList();
                                // 添加成功后清空搜索条件，回退到首页
                                this.queryGroupInfo.pageIndex = 1;
                                if (this.type === 2) {
                                    // 夺旗赛需要自动分配题目
                                    allotTopic2Team({
                                        sceneId: this.$route.query.id,
                                        groupTO: {
                                            partyId: data.data.partyId,
                                            partyName: data.data.partyName,
                                            teamId: data.data.id,
                                            teamName: data.data.name,
                                        },
                                    })
                                        .then(({ code, message }) => {
                                            if (code !== 1) {
                                                this.$Message.warning(message);
                                            }
                                        })
                                        .catch((error) => {
                                            this.$Message.error('自动分配题目异常，请手动分配');
                                        });
                                }
                            } else {
                                this.cancelLoading('accessGroupModal');
                                this.$Message.warning(data.message);
                            }
                        });
                    } else {
                        let path = {
                            groupId: this.groupFormValidate.id,
                        };
                        modifyaccessgroup(path, params).then((data) => {
                            if (data.code == 1) {
                                this.accessGroupModal.show = false;
                                this.getAccessGroupList();
                            } else {
                                setTimeout(() => {
                                    this.cancelLoading('accessGroupModal');
                                }, 500);
                                this.$Message.warning(data.message);
                            }
                        });
                    }
                } else {
                    this.cancelLoading('accessGroupModal');
                }
            });
        },
        // 删除团队
        delAccessGroup(group) {
            let userIds = group.userList.map((user) => user.userId);
            if (userIds.length > 0) {
                this.delTeam = true;
                this.delSceneUsers(userIds); // 级联删除团队成员
            }
            delaccessgroup(group.id).then((data) => {
                if (data.code == 1) {
                    this.$Message.info(`删除${this.type === 10 ? '角色' : '团队'}成功`);
                    this.$emit('del-data');
                    this.setRefreshChatRoom(new Date().getTime()); // 删除团队，需要记录时间点，通过vuex通知聊天室更新用户列表
                    this.setRefresTimestamp(); // 提示聊天室需要更新用户列表
                    if (this.type == 2) {
                        // 夺旗赛删除团队分配的题目需要使用新接口
                        this.delAssignedTopics(group.id);
                    } else {
                        this.delGroupTarget(group.id);
                    }
                    if (this.type === 5) {
                        // 护网演练需要额外删除已分配的目标
                        this.delTeamTarget(this.$route.query.id, group.id);
                    }
                    // 删除后展示当前页，当前页没有数据展示前一页
                    this.queryGroupInfo.pageIndex =
                        this.accessGroupList.length == 1 && this.queryGroupInfo.pageIndex > 1
                            ? this.queryGroupInfo.pageIndex - 1
                            : this.queryGroupInfo.pageIndex;
                    this.getAllAccessList();
                    this.getAccessGroupList();
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 删除团队下已分配的目标
        delTeamTarget(sceneId, teamId) {
            delTeamTarget(sceneId, teamId)
                .then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('删除团队下已分配的目标异常');
                });
        },
        // 夺旗赛删除已经分配的题目
        delAssignedTopics(teamId) {
            delAssignedTopics(this.$route.query.id, teamId)
                .then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('删除团队下已分配的靶机异常');
                });
        },
        // 查询团队已分配的接入组
        getNetworkDetails(group) {
            getUserInstanceExclude({
                testId: this.$route.query.id,
                pageIndex: 1,
                pageSize: 10,
                accessGroupId: group.id,
            }).then(({ code, data = {} }) => {
                if (code === 1) {
                    data = data.data || [];
                    let instance = data.length ? data[0] : {};
                    if (instance.deviceList && instance.deviceList.length) {
                        getDeviceList(this.projectId, {
                            id: instance.deviceList[0].deviceId,
                        }).then(({ code, data = {} }) => {
                            if (code === 1) {
                                let network = data && data.list && data.list[0] && data.list[0];
                                this.$set(group, 'networkId', network && network.networkId);
                            }
                        });
                    }
                }
            });
        },
        // 获取团队外网IP
        getOptionalVms(group) {
            let params = {
                page: 1,
                pageSize: 10000,
                sortBy: 'name',
                order: 'asc',
                vmType: 'PRT',
                party: Number(group.partyId),
                findPorts: true,
            };
            getDeviceList(this.projectId, params).then((data) => {
                if (data.code == 1 && data.data.list.length > 0) {
                    let address = data.data.list[0].address;
                    if (!this.allowChangeIp) {
                        // 不允许切换外网ip时，这个值才有设置
                        let publicNetworkList = address.filter(
                            (item) => item.name.split('-').pop() == '公网'
                        );
                        if (publicNetworkList.length) {
                            this.$set(
                                group,
                                'ip',
                                publicNetworkList[0].ips &&
                                    publicNetworkList[0].ips[0] &&
                                    publicNetworkList[0].ips[0].ipAddress
                            );
                        }
                    }
                }
            });
        },
        // 切换环境
        batchUserToDevice() {
            // 1.切换人员设备 2.切换环境修改题目vmId3.夺旗赛添加任务人员机器配置
            if (!this.selBackupSubnet) {
                this.$Message.warning('请选择环境');
                this.cancelLoading('accessNetworkModal');
                return;
            }
            let group = this.accessNetworkModal.group;
            if (this.targetAllotTotal > 0) {
                // 有分配的题目时，切换题目vmId
                this.switchCtfGameBox().then((data) => {
                    if (data === 1) {
                        let userList = group.userList;
                        let proArr = [];
                        // 非夺旗赛或虚拟接入的夺旗赛，需要同步切换虚拟机，实物接入的夺旗赛至“选手自带答题设备接入申请”手动切换
                        if (this.type !== 2 || this.vmInEnable) {
                            proArr = userList.map((user) => {
                                return this.deviceToUser(group, user, this.networkVms);
                            });
                        }
                        Promise.all(proArr)
                            .then((data) => {
                                // 操作完毕，不需要提示什么
                            })
                            .catch((error) => {
                                this.$Message.error(error[0]);
                                this.cancelLoading('accessNetworkModal');
                            });
                    }
                    if (this.type == 1) {
                        //攻防赛
                        this.getVmList(group); // mixin定义，处理flag持续提交任务
                    }
                });
            } else {
                this.getAccessGroupList();
                this.$Message.info('环境切换成功！');
                if (this.allowSwitchingEnvironments) {
                    this.sendChangeEnvironBoard(group);
                }
                this.accessNetworkModal.show = false;
                this.cancelLoading('accessNetworkModal');
            }
        },
        // 切换环境时，切换虚拟机
        deviceToUser(group, user, vms) {
            return new Promise((resolve, reject) => {
                let devices = [];
                devices = vms.map((vm) => {
                    return {
                        deviceId: vm.id,
                        deviceName: vm.name,
                        deviceType: 'VM',
                        enableRecordScreen: true,
                        enabled: true,
                    };
                });
                let params = {
                    accessGroupId: group.id,
                    devices: devices,
                    testId: this.$route.query.id,
                    userId: user.userId,
                };
                setuservmrelation(params).then((data) => {
                    if (data.code == 1) {
                        resolve();
                    } else {
                        reject(data.message);
                        this.$Message.warning(data.message);
                    }
                });
            });
        },
        //切换环境修改题目vmId
        switchCtfGameBox() {
            return new Promise((resolve, reject) => {
                let team = this.accessNetworkModal.group;
                let data = {
                    teamId: team.id,
                    networkId: this.selBackupSubnet,
                    projectId: this.$route.query.prjid,
                    teamName: team.name,
                };
                switchCtfGameBox(this.testId, data)
                    .then((data) => {
                        if (data.code == 1) {
                            this.getAccessGroupList();
                            this.$Message.info('环境切换成功！');
                            this.accessNetworkModal.show = false;
                            resolve(1);
                        } else {
                            this.$Message.error(data.message);
                            this.cancelLoading('accessNetworkModal');
                            resolve(0);
                        }
                    })
                    .catch((error) => {
                        this.$Message.error('环境切换失败');
                        this.cancelLoading('accessNetworkModal');
                        resolve(0);
                    });
            });
        },
        // 模态框切换loading状态，使确定按钮可以点击
        cancelLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        // 删除场景中的接入用户
        delSceneUsers(userIds) {
            delsceneusers(this.testId, userIds).then((data) => {
                if (data.code == 1) {
                    if (!this.delTeam) {
                        // 删除团队的操作时，不需要提示信息
                        this.$Message.info('操作成功');
                    }
                    // 操作结束后，重置delTeam
                    this.delTeam = false;
                } else {
                    this.$Message.warning(data.message);
                }
            });
        },
        // 查询工程详情
        getProjectInfo() {
            getstatusbyprjid(this.$route.query.prjid).then((data) => {
                if (data.code == 1) {
                    this.projectInfo = data.attribute;
                    this.getProjectSubnet();
                }
            });
        },
        // 查询可用的子网环境
        getProjectSubnet() {
            queryNetworkList(this.$route.query.prjid, this.projectInfo.network.id).then((data) => {
                if (data.code == 1) {
                    let subnetList = [];
                    data.attribute.editorStage.childs.forEach((item) => {
                        subnetList = subnetList.concat(item.childs);
                    });
                    this.subnetList = subnetList.filter((subnet) => subnet.dataType == 'NW'); // 获取类型为NW的子网列表
                    if (this.allowSwitchingEnvironments) {
                        this.backupSubnetList = this.subnetList;
                        if (this.type == 2) {
                            this.queryTargetAllot();
                        } else if ([1, 8, 9].includes(this.type)) {
                            this.queryTargetAllotAdc();
                        }
                    }
                }
            });
        },
        // 获取备用子网络包含的机器
        getAllVms(networkId) {
            let params = {
                page: 1,
                pageSize: 100000,
                sortBy: 'name',
                order: 'asc',
                findPorts: true,
                networkId: networkId,
            };
            if ([1, 2, 4, 5, 8, 9].includes(this.type)) {
                // 攻防、夺旗、渗透、护网，额外设置参数
                params.vmType = 'CLIENT';
            }
            getDeviceList(this.projectId, params).then((data) => {
                if (data.code == 1) {
                    if (this.type == 2) {
                        // 视情况过滤掉不需要切换的虚拟机
                        if (this.onlineMode == 0) {
                            // 线下才有虚拟选手
                            this.networkVms = data.data.list.filter(
                                (vm) =>
                                    vm.name.indexOf('虚拟选手') != -1 &&
                                    vm.address[0].ips[0].ipAddress.indexOf('192.168.20') != -1
                            );
                        } else {
                            this.networkVms = data.data.list.filter(
                                (vm) => vm.address[0].ips[0].ipAddress.indexOf('192.168.20') != -1
                            );
                        }
                    } else if ([1, 8, 9].includes(this.type)) {
                        this.networkVms = data.data.list.filter(
                            (vm) => vm.address[0].ips[0].ipAddress.indexOf('192.168.20') != -1
                        );
                        if (this.type === 9) {
                            // // 运维赛在获取接入机器时，还要额外获取安全运维赛题的虚拟机作为接入机器
                            Promise.all([
                                getTargetTeamList_new({
                                    pageIndex: 1,
                                    pageSize: 10,
                                    sceneId: this.$route.query.id,
                                    projectId: this.$route.query.prjid,
                                }),
                                getDeviceList(this.projectId, {
                                    page: 1,
                                    pageSize: 100000,
                                    sortBy: 'name',
                                    order: 'asc',
                                    findPorts: true,
                                    networkId: networkId,
                                    vmType: 'SERVER',
                                }),
                            ]).then(([res1, res2]) => {
                                let opQuestionNames = [];
                                if (res1.code !== 1) {
                                    this.$Message.warning(res1.message);
                                    return;
                                }
                                res1.data.items.forEach((item) => {
                                    if (item.category === '安全运维') {
                                        opQuestionNames.push(item.name);
                                    }
                                });
                                if (res2.code !== 1) {
                                    this.$Message.warning(res2.message);
                                    return;
                                }
                                let vms = [];
                                if (res2.code !== 1) {
                                    this.$Message.warning(res1.message);
                                    return;
                                }
                                vms = res2.data.list.filter((item) =>
                                    opQuestionNames.includes(item.name)
                                );
                                this.networkVms = this.networkVms.concat(vms);
                            });
                        }
                    } else {
                        this.networkVms = data.data.list;
                    }
                }
            });
        },
        // 获取夺旗赛类型题目分配情况
        queryTargetAllot() {
            let params = {
                pageIndex: 1,
                pageSize: 2147483647,
                sceneId: this.$route.query.id,
            };
            return new Promise((resolve, reject) => {
                queryCtfTargetAllot(params)
                    .then((data) => {
                        if (data.code == 1) {
                            // 保留可以访问，需要提交静态Flag的机器
                            this.targetAllotList = data.data.items.filter(
                                (vm) =>
                                    vm.url 
                                // 23327 不需要过滤任何flag  切换环境的时候。
                                    // && 
                                    // vm.isFixedFileFlag == '1' &&
                                    // vm.isNeedSubmitFlag == '1'
                            );
                            this.targetAllotTotal = this.targetAllotList.length;
                            resolve();
                        } else {
                            this.$Message.warning(data.message);
                        }
                    })
                    .catch((error) => {
                        this.$Message.error(error);
                    });
            });
        },
        // 查询攻防赛题目分配情况
        queryTargetAllotAdc() {
            let params = {
                pageIndex: 1,
                pageSize: 2147483647,
                sceneId: this.$route.query.id,
            };
            return new Promise((resolve, reject) => {
                queryTargetAllot(params)
                    .then((data) => {
                        if (data.code == 1) {
                            // 攻防赛需要过滤掉备用环境的分配情况
                            this.targetAllotList = (data.data.items || []).filter(
                                (item) => !item.spare
                            );
                            this.targetAllotTotal = data.data.total;
                            resolve();
                        } else {
                            this.$Message.warning(data.message);
                        }
                    })
                    .catch((error) => {
                        this.$Message.error(error);
                    });
            });
        },
        // 夺旗赛外的其他类型，删除已分配的题目、任务
        delGroupTarget(groupId) {
            delGroupTarget(this.$route.query.id, groupId)
                .then(({ code, message }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('删除团队下已分配的靶机异常');
                });
        },
        // 获取返回用户的在线状态
        getCompanyUsersInfo(userId) {
            return new Promise((resolve, reject) => {
                getCompanyUsersInfo(userId).then((data) => {
                    if (data.code == 1) {
                        resolve(data.data.online);
                    } else {
                        // 查询有误时，特意不提示错误信息，无法展示在线状态即可，避免查看非自身单位的人员出现错误提示。
                        resolve(false);
                    }
                });
            });
        },
        // 获取用户登录ip
        getUserLoginIP(userIds) {
            return new Promise((resolve, reject) => {
                getUserLoginIP(userIds).then((data) => {
                    if (data.code == 1) {
                        // 降序排列，便于拿到最近的登陆时间
                        resolve(
                            data.data.sort(
                                (a, b) =>
                                    new Date(b.loginTime).getTime() -
                                    new Date(a.loginTime).getTime()
                            )
                        );
                    } else {
                        this.$Message.warning(data.message);
                        resolve('');
                    }
                });
            });
        },
        // 封禁团队
        banAccessGroup(group) {
            banAccessGroup_new(this.$route.query.id, group.id).then((data) => {
                if (data.code == 1) {
                    this.$Message.info('封禁成功');
                    this.getAccessGroupList();
                } else {
                    this.$Message.warning(`${data.message}，封禁失败`);
                }
            });
        },
        // 解禁团队
        allowAccessGroup(group) {
            allowAccessGoup_new(this.$route.query.id, group.id).then((data) => {
                if (data.code == 1) {
                    this.$Message.info('解禁成功');
                    this.getAccessGroupList();
                } else {
                    this.$Message.warning(`${data.message}，解禁失败`);
                }
            });
        },
        // 类型转义为中文
        typeFilter(val) {
            let str = '';
            switch (val) {
                case 0:
                    str = '对抗演练';
                    break;
                case 1:
                    str = '攻防赛';
                    break;
                case 2:
                    str = '夺旗赛';
                    break;
                case 3:
                    str = '知识赛';
                    break;
                case 4:
                    str = '渗透演练';
                    break;
                case 5:
                    str = '护网演练';
                    break;
                case 7:
                    str = '综合演练';
                    break;
                case 8:
                    str = '攻防赛Plus';
                    break;
                case 9:
                    str = '运维赛';
                    break;
                default:
                    break;
            }
            return str;
        },
        // 切换环境发送公告
        sendChangeEnvironBoard(group) {
            let sceneId = this.$route.query.id;
            let sceneName = this.$route.query.name;
            let sceneType = this.typeFilter(this.type);
            let params = {
                sceneId: sceneId,
                noticeSceneDto: {
                    accessGroups: [
                        {
                            groupId: group.id,
                            userIds: group.userList.map((user) => user.userId),
                        },
                    ],
                    content: `${sceneType}:团队 [ ${group.name} ] 在 [ ${sceneName} ] 场景中环境已切换`,
                    id: '',
                    title: '2/' + this.type + '/' + sceneId, //传递场景类型-场景Id(这个字段暂时没用，为了实现功能，暂时作为自定义字段，推送切换环境消息)
                    type: 1,
                },
            };
            sendToSence(params).then((data) => {
                if (data.code != 1) {
                    this.$Message.error(data.message);
                }
            });
        },
        // 判断当前组的封禁状态
        groupBanned(group) {
            // 没有成员默认未封禁，所有队员都是禁用状态，团队封禁
            return (
                group.userList.length > 0 && group.userList.every((user) => user.banned === true)
            );
        },
        // 导出用户信息，当前版本该功能暂时隐藏
        doOutputUser() {
            let projectId = this.$route.query.prjid;
            outputUser(projectId).then((data) => {
                let url = window.URL.createObjectURL(data); //表示一个指定的file对象或Blob对象
                let a = document.createElement('a');
                document.body.appendChild(a);
                let fileName = this.$route.query.name + '用户下载.xls'; //filename名称截取
                a.href = url;
                a.download = fileName; //命名下载名称
                a.click(); //点击触发下载
                window.URL.revokeObjectURL(url); //下载完成进行释放
            });
        },
    },
};
</script>

<style scoped>
#accessUser .userModel{
    display: flex;
    flex-wrap: wrap;
}
.userModel .user_list_line{
    display: inline-block;
    width: 0;
    height: 100%;
    margin: 0 8px;
    vertical-align: middle;
}
</style>
<style>
#access .demo-table-info-row > td {
    background: lightblue;
}
#access .ivu-table-overflowX {
    overflow-x: hidden;
}
</style>
